#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
查看数据库中的所有信息
"""

import os
import sys
import django

# 设置Django环境
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TradingPlatform_Server.settings')
django.setup()

from Server.models import (
    User, Store, Takeout, Menu, Address, 
    Order, Payment, Message, Discuss, Delivery, Kind
)

def show_line(char="-", length=100):
    """显示分隔线"""
    print(char * length)

def show_title(title):
    """显示标题"""
    print("\n" + "="*100)
    print(" " * 40 + title)
    print("="*100)

def view_users():
    """查看用户表"""
    show_title("用户表 (Server_user)")
    
    users = User.objects.all()
    print("\n总记录数: %d\n" % users.count())
    
    if users.count() > 0:
        show_line()
        print("%-12s %-15s %-20s %-15s %-10s %-10s" % (
            "ID", "手机号", "昵称", "密码", "余额", "管理员"
        ))
        show_line()
        
        for user in users:
            is_admin = "是" if user.is_admin else "否"
            print("%-12s %-15s %-20s %-15s %-10.2f %-10s" % (
                user.id,
                user.phone,
                user.username[:20] if len(user.username) > 20 else user.username,
                user.password,
                user.money,
                is_admin
            ))
        show_line()

def view_stores():
    """查看店铺表"""
    show_title("店铺表 (Server_store)")
    
    stores = Store.objects.all()
    print("\n总记录数: %d\n" % stores.count())
    
    if stores.count() > 0:
        show_line()
        print("%-12s %-20s %-15s %-30s %-10s" % (
            "ID", "店铺名称", "联系电话", "地址", "状态"
        ))
        show_line()
        
        for store in stores:
            status = "已通过" if store.is_pass else "待审核"
            print("%-12s %-20s %-15s %-30s %-10s" % (
                store.id,
                store.name[:20],
                store.phone,
                (store.address[:30] if hasattr(store, 'address') else 'N/A'),
                status
            ))
        show_line()

def view_takeouts():
    """查看外卖表"""
    show_title("外卖表 (Server_takeout)")
    
    takeouts = Takeout.objects.all()
    print("\n总记录数: %d\n" % takeouts.count())
    
    if takeouts.count() > 0:
        show_line()
        print("%-12s %-25s %-10s %-15s %-10s" % (
            "ID", "外卖名称", "价格", "店铺ID", "状态"
        ))
        show_line()
        
        for takeout in takeouts:
            status = "已通过" if takeout.is_pass else "待审核"
            print("%-12s %-25s %-10.2f %-15s %-10s" % (
                takeout.id,
                takeout.name[:25],
                takeout.price,
                takeout.store_id,
                status
            ))
        show_line()

def view_orders():
    """查看订单表"""
    show_title("订单表 (Server_order)")
    
    orders = Order.objects.all()
    print("\n总记录数: %d\n" % orders.count())
    
    if orders.count() > 0:
        show_line()
        print("%-12s %-15s %-12s %-10s %-10s %-20s" % (
            "ID", "用户ID", "外卖ID", "数量", "总价", "创建时间"
        ))
        show_line()
        
        for order in orders[:50]:  # 只显示前50条
            create_time = order.create_time.strftime('%Y-%m-%d %H:%M') if hasattr(order, 'create_time') else 'N/A'
            print("%-12s %-15s %-12s %-10d %-10.2f %-20s" % (
                order.id,
                order.user_id,
                order.takeout_id,
                order.num,
                order.total_price,
                create_time
            ))
        
        if orders.count() > 50:
            print("\n... 还有 %d 条记录未显示 ..." % (orders.count() - 50))
        show_line()

def view_addresses():
    """查看地址表"""
    show_title("地址表 (Server_address)")
    
    addresses = Address.objects.all()
    print("\n总记录数: %d\n" % addresses.count())
    
    if addresses.count() > 0:
        show_line()
        print("%-12s %-15s %-15s %-15s %-30s %-10s" % (
            "ID", "用户ID", "学校", "校区", "详细地址", "默认"
        ))
        show_line()
        
        for addr in addresses:
            is_default = "是" if addr.is_default else "否"
            school = addr.school[:15] if hasattr(addr, 'school') else 'N/A'
            campus = addr.campus[:15] if hasattr(addr, 'campus') else 'N/A'
            detail = addr.detail[:30] if hasattr(addr, 'detail') else 'N/A'
            
            print("%-12s %-15s %-15s %-15s %-30s %-10s" % (
                addr.id,
                addr.user_id,
                school,
                campus,
                detail,
                is_default
            ))
        show_line()

def view_menus():
    """查看菜单表"""
    show_title("菜单表 (Server_menu)")
    
    menus = Menu.objects.all()
    print("\n总记录数: %d\n" % menus.count())
    
    if menus.count() > 0:
        show_line()
        print("%-12s %-15s %-12s %-10s" % (
            "ID", "用户ID", "外卖ID", "数量"
        ))
        show_line()
        
        for menu in menus[:50]:
            print("%-12s %-15s %-12s %-10d" % (
                menu.id,
                menu.user_id,
                menu.takeout_id,
                menu.num
            ))
        
        if menus.count() > 50:
            print("\n... 还有 %d 条记录未显示 ..." % (menus.count() - 50))
        show_line()

def view_payments():
    """查看支付表"""
    show_title("支付表 (Server_payment)")
    
    payments = Payment.objects.all()
    print("\n总记录数: %d\n" % payments.count())
    
    if payments.count() > 0:
        show_line()
        print("%-12s %-15s %-12s %-10s %-20s" % (
            "ID", "用户ID", "订单ID", "金额", "创建时间"
        ))
        show_line()
        
        for payment in payments[:50]:
            create_time = payment.create_time.strftime('%Y-%m-%d %H:%M') if hasattr(payment, 'create_time') else 'N/A'
            print("%-12s %-15s %-12s %-10.2f %-20s" % (
                payment.id,
                payment.user_id,
                payment.order_id if hasattr(payment, 'order_id') else 'N/A',
                payment.money,
                create_time
            ))
        
        if payments.count() > 50:
            print("\n... 还有 %d 条记录未显示 ..." % (payments.count() - 50))
        show_line()

def view_messages():
    """查看消息表"""
    show_title("消息表 (Server_message)")
    
    messages = Message.objects.all()
    print("\n总记录数: %d\n" % messages.count())
    
    if messages.count() > 0:
        show_line()
        print("%-12s %-15s %-50s %-20s" % (
            "ID", "用户ID", "内容", "创建时间"
        ))
        show_line()
        
        for msg in messages[:30]:
            content = msg.content[:50] if hasattr(msg, 'content') else 'N/A'
            create_time = msg.create_time.strftime('%Y-%m-%d %H:%M') if hasattr(msg, 'create_time') else 'N/A'
            print("%-12s %-15s %-50s %-20s" % (
                msg.id,
                msg.user_id,
                content,
                create_time
            ))
        
        if messages.count() > 30:
            print("\n... 还有 %d 条记录未显示 ..." % (messages.count() - 30))
        show_line()

def view_discusses():
    """查看评论表"""
    show_title("评论表 (Server_discuss)")
    
    discusses = Discuss.objects.all()
    print("\n总记录数: %d\n" % discusses.count())
    
    if discusses.count() > 0:
        show_line()
        print("%-12s %-15s %-12s %-50s" % (
            "ID", "用户ID", "外卖ID", "评论内容"
        ))
        show_line()
        
        for discuss in discusses[:30]:
            content = discuss.content[:50] if hasattr(discuss, 'content') else 'N/A'
            print("%-12s %-15s %-12s %-50s" % (
                discuss.id,
                discuss.user_id,
                discuss.takeout_id,
                content
            ))
        
        if discusses.count() > 30:
            print("\n... 还有 %d 条记录未显示 ..." % (discusses.count() - 30))
        show_line()

def view_deliveries():
    """查看配送表"""
    show_title("配送表 (Server_delivery)")
    
    deliveries = Delivery.objects.all()
    print("\n总记录数: %d\n" % deliveries.count())
    
    if deliveries.count() > 0:
        show_line()
        print("%-12s %-15s %-15s %-10s" % (
            "ID", "订单ID", "配送员", "状态"
        ))
        show_line()
        
        for delivery in deliveries[:50]:
            print("%-12s %-15s %-15s %-10s" % (
                delivery.id,
                delivery.order_id if hasattr(delivery, 'order_id') else 'N/A',
                delivery.deliveryman if hasattr(delivery, 'deliveryman') else 'N/A',
                delivery.status if hasattr(delivery, 'status') else 'N/A'
            ))
        
        if deliveries.count() > 50:
            print("\n... 还有 %d 条记录未显示 ..." % (deliveries.count() - 50))
        show_line()

def view_kinds():
    """查看分类表"""
    show_title("分类表 (Server_kind)")
    
    kinds = Kind.objects.all()
    print("\n总记录数: %d\n" % kinds.count())
    
    if kinds.count() > 0:
        show_line()
        print("%-12s %-30s %-50s" % (
            "ID", "分类名称", "描述"
        ))
        show_line()
        
        for kind in kinds:
            name = kind.name[:30] if hasattr(kind, 'name') else 'N/A'
            desc = kind.description[:50] if hasattr(kind, 'description') else 'N/A'
            print("%-12s %-30s %-50s" % (
                kind.id,
                name,
                desc
            ))
        show_line()

def view_all():
    """查看所有数据库信息"""
    
    print("\n\n")
    print("*" * 100)
    print("*" + " " * 30 + "数据库完整信息查看工具" + " " * 30 + "*")
    print("*" * 100)
    
    # 统计信息
    show_title("数据统计")
    print("\n")
    print("%-20s : %d 条" % ("用户", User.objects.count()))
    print("%-20s : %d 条" % ("店铺", Store.objects.count()))
    print("%-20s : %d 条" % ("外卖", Takeout.objects.count()))
    print("%-20s : %d 条" % ("订单", Order.objects.count()))
    print("%-20s : %d 条" % ("地址", Address.objects.count()))
    print("%-20s : %d 条" % ("菜单", Menu.objects.count()))
    print("%-20s : %d 条" % ("支付记录", Payment.objects.count()))
    print("%-20s : %d 条" % ("消息", Message.objects.count()))
    print("%-20s : %d 条" % ("评论", Discuss.objects.count()))
    print("%-20s : %d 条" % ("配送", Delivery.objects.count()))
    print("%-20s : %d 条" % ("分类", Kind.objects.count()))
    print("\n")
    
    # 详细信息
    view_users()
    view_stores()
    view_takeouts()
    view_orders()
    view_addresses()
    view_menus()
    view_payments()
    view_messages()
    view_discusses()
    view_deliveries()
    view_kinds()
    
    # 结束
    print("\n\n")
    print("*" * 100)
    print("*" + " " * 35 + "查看完成" + " " * 35 + "*")
    print("*" * 100)
    print("\n")

if __name__ == '__main__':
    try:
        view_all()
    except Exception as e:
        print("\n[错误] %s" % str(e))
        import traceback
        traceback.print_exc()

